function [ omega, sonar_data , n_A] = collision_avoidance(n_A, omega)
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here

global d_min_obst c_acc_flee timestep obst_det

% auxiliry variables
gamma = pi/2:-pi/7:-pi/2;

% detection of obstacles  
sonar_data = pioneer_read_sonars();
      
% flag showing if obstacle was detected
obst_det = 0;

    % obstacle detected (distance to obstacle smaller than min value)
if ~isempty(find(sonar_data < d_min_obst*10^3,1)) %&& SONAR_on       
    obst_det = 1;
    [sound1, sound2] = audioread('button.wav');
    sound(sound1, sound2);
    
    [sonar_data_min ,sonar_data_min_ind ] = min(sonar_data);       

    % determination of correction angle
    if sonar_data_min_ind <= 4  % obstacle on the left hand          
        if sonar_data_min_ind == 1              
            phi = (gamma(2) - pi/2)/2;               
        else                
            phi = (gamma(sonar_data_min_ind) - pi/2);                
        end           
    else    % obstacle on the right hand         
        if sonar_data_min_ind == 8               
            phi = (gamma(7) + pi/2)/2;               
        else               
            phi = (gamma(sonar_data_min_ind) + pi/2);               
        end           
    end
    phi = phi*c_acc_flee; % smooth the evasion by factor

    % correction of angular velocity        
    omega = radtodeg(phi)/timestep;    
    
    % number of avoidance events
    n_A = n_A + 1;

end
    

